﻿/*
 * KLF Headless Browser
 * Written by Kris Oye <kristianoye@gmail.com>
 * Copyright (C) 2011-2012.  All rights reserved.
 */
namespace KLF.Lib.Browser.DOM
{
    #region Using Statements

    using System;

    #endregion

    public class Text : CharacterData
    {
        #region Constructors

        internal Text(Text text)
            : base(text.ownerDocument, text.data)
        {
        }

        internal Text(Text node, int offset)
            : base(node.ownerDocument, node.data.Substring(offset))
        {
        }

        internal Text(Document owner, string text)
            : base(owner, text)
        {
        }

        #endregion

        #region Methods

        public override string ToString()
        {
            return String.Format("Text[{0}]",
                !StringLookup.IsNullOrEmpty(_data) && 
                _data.Value.Length > 10 ?
                    _data.Value.Substring(0, 10) : _data.Value);
        }

        #endregion

        #region Non-Standard Methods

        public string outerHTML
        {
            get
            {
                return data;
            }
        }

        #endregion

        #region DOM Level 1 Compliance

        public override Node cloneNode(bool deep)
        {
            return new Text(this);
        }

        public override string nodeName
        {
            get { return "#text"; }
        }

        public override string nodeValue
        {
            get { return data; }
        }

        public override byte nodeType
        {
            get { return TEXT_NODE; }
        }

        /// <summary>
        /// Breaks this Text node into two Text nodes at the specified offset,
        /// keeping both in the tree as siblings. This node then only contains
        /// all the content up to the offset point. And a new Text node, which
        /// is inserted as the next sibling of this node, contains all the 
        /// content at and after the offset point. 
        /// </summary>
        /// <param name="offset">The offset at which to split, starting from 0.</param>
        /// <returns>The new Text node.</returns>
        public Text splitText(int offset)
        {
            if (offset > data.Length)
            {
                if (Parent != null)
                {
                    int index = Parent.Children.IndexOf(this);
                    Text newText = new Text(this, offset);

                    data = data.Substring(0, offset - 1);
                    Parent.insertChild(index + 1, newText);

                    return newText;
                }
            }
            throw new Exception("INDEX_SIZE_ERR");
        }

        #endregion
    }
}
